package com.stylefeng.guns.order.modular.order.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.dubbo.rpc.RpcContext;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.api.cinema.CinemaServiceApi;
import com.stylefeng.guns.api.cinema.vo.FilmInfoVO;
import com.stylefeng.guns.api.cinema.vo.OrderQueryVO;
import com.stylefeng.guns.api.order.OrderServiceApi;
import com.stylefeng.guns.api.order.vo.OrderVO;
import com.stylefeng.guns.core.util.UUIDUtil;
import com.stylefeng.guns.order.common.persistence.dao.MoocOrder2018TMapper;
import com.stylefeng.guns.order.common.persistence.model.MoocOrder2018T;
import com.stylefeng.guns.order.common.persistence.model.MoocOrderT;
import com.stylefeng.guns.order.common.util.FTPUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @auther: madison
 * @date: 2018/11/12 22:23
 * @description:
 */
@Slf4j
@Component
@Service(interfaceClass = OrderServiceApi.class, group = "order2018", filter = "tracing")
public class OrderServiceImpl2018 implements OrderServiceApi{

    @Autowired
    private MoocOrder2018TMapper moocOrder2018TMapper;

    @Reference(interfaceClass = CinemaServiceApi.class, check = false)
    private CinemaServiceApi cinemaServiceApi;

    @Autowired
    private FTPUtil ftpUtil;

    @Override
    public boolean isTrueSeats(String fieldId, String seats) {
        // 根据fieldId找到对应的座位位置图
        String seatPath = moocOrder2018TMapper.getSeatsByFieldId(fieldId);

        // 读取位置图，判断seats是否为真
        String fileStrByAddress = ftpUtil.getFileStrByAddress(seatPath);

        // 将fileStrByAddress 转换为JSON对象
        JSONObject jsonObject = JSONObject.parseObject(fileStrByAddress);
        // seats = 1,2,3  ids=1,3,4,5,6,7,88
        String ids = jsonObject.get("ids").toString();

        // 每一次匹配上的, 都给isTrue+1
        String[] seatArrs = seats.split(",");
        String[] idArrs = ids.split(",");
        int isTrue = 0;
        for(String id : idArrs){
            for(String seat : seatArrs){
                if(seat.equalsIgnoreCase(id)){
                    isTrue++;
                }
            }
        }

        // 如果匹配上的数量与已售座位一致，则表示全都匹配上
        if(seatArrs.length == isTrue){
            return true;
        }

        return false;
    }

    @Override
    public boolean isNotSoldSeats(String fieldId, String seats) {
        EntityWrapper entityWrapper = new EntityWrapper();
        entityWrapper.eq("field_id", fieldId);

        List<MoocOrder2018T> list = moocOrder2018TMapper.selectList(entityWrapper);
        String[] seatArrs = seats.split(",");

        // 有任何一个编号匹配上，则直接返回失败
        for (MoocOrder2018T moocOrder2018T : list){
            String[] ids = moocOrder2018T.getSeatsIds().split(",");
            for(String id : ids){
                for(String seat : seatArrs){
                    if(id.equalsIgnoreCase(seat)){
                        return false;
                    }
                }
            }
        }

        return true;
    }

    @Override
    public OrderVO saveOrderInfo(Integer fieldId, String soldSeats, String seatsName, Integer userId) {
        // 编号
        String uuid = UUIDUtil.genUuid();

        // 影片信息
        FilmInfoVO filmInfoVO = cinemaServiceApi.getFilmInfoByFieldId(fieldId);
        Integer filmId = Integer.parseInt(filmInfoVO.getFilmId());

        // 获取影院信息
        OrderQueryVO orderQueryVO = cinemaServiceApi.getOrderNeeds(fieldId);
        Integer cinemaId = Integer.parseInt(orderQueryVO.getCinemaId());
        double filmPrice = Double.parseDouble(orderQueryVO.getFilmPrice());

        // 求订单总金额 1,2,3,4,5
        int solds = soldSeats.split(",").length;
        double totalPrice = getTotalPrice(solds, filmPrice);

        MoocOrder2018T moocOrder2018T = new MoocOrder2018T();
        moocOrder2018T.setUuid(uuid);
        moocOrder2018T.setSeatsName(seatsName);
        moocOrder2018T.setSeatsIds(soldSeats);
        moocOrder2018T.setOrderUser(userId);
        moocOrder2018T.setOrderPrice(totalPrice);
        moocOrder2018T.setFilmPrice(filmPrice);
        moocOrder2018T.setFilmId(filmId);
        moocOrder2018T.setFieldId(fieldId);
        moocOrder2018T.setCinemaId(cinemaId);
        Integer insert = moocOrder2018TMapper.insert(moocOrder2018T);
        if(insert > 0){
            // 返回查询结果
            OrderVO orderVO = moocOrder2018TMapper.getOrderInfoById(uuid);
            if(orderVO == null | orderVO.getOrderId() == null){
                log.error("订单查询失败,订单编号为{}", uuid);
                return null;
            }else{
                return orderVO;
            }
        }else{
            // 返回出错
            log.error("订单插入失败");
        }

        return null;
    }

    private double getTotalPrice(int solds, double filmPrice){
        BigDecimal soldDeci = new BigDecimal(solds);
        BigDecimal filmPriceDeci = new BigDecimal(filmPrice);

        BigDecimal result = soldDeci.multiply(filmPriceDeci);
        // 四舍五入取小数点后两位
        result.setScale(2, BigDecimal.ROUND_HALF_UP);
        return result.doubleValue();
    }

    @Override
    public Page<OrderVO> getOrderByUserId(Integer userId, Page<OrderVO> page) {
        Page<OrderVO> result = new Page<>();
        if(userId == null){
            log.error("订单查询业务失败，用户编号未传入");
            return null;
        }else{
            List<OrderVO> orders = moocOrder2018TMapper.getOrdersByUserId(userId, page);
            if(orders == null || orders.size() == 0){
                result.setTotal(0);
                result.setRecords(new ArrayList<>());
                return result;
            }else{
                // 获取订单总数
                EntityWrapper entityWrapper = new EntityWrapper();
                entityWrapper.eq("order_user", userId);
                Integer count = moocOrder2018TMapper.selectCount(entityWrapper);
                // 结果放入Page
                result.setTotal(count);
                result.setRecords(orders);
                return result;
            }
        }
    }

    @Override
    public String getSoldSeatByFieldId(Integer fieldId) {
        if(fieldId == null){
            log.error("查询已售座位错误,未传入任何场次编号");
            return null;
        }else{
            String seatIds = moocOrder2018TMapper.getSoldSeatsByFieldId(fieldId);
            return seatIds;
        }
    }

    @Override
    public OrderVO getOrderInfoById(String orderId) {
        OrderVO orderVO = moocOrder2018TMapper.getOrderInfoById(orderId);
        return orderVO;
    }

    @Override
    public boolean paySuccess(String orderId) {
        // 看看是否有当前登陆人
        String userId = RpcContext.getContext().getAttachment("userId");
        log.info("DefaultAlipayServiceImpl - getOrderStatus - userId = " + userId);

        MoocOrder2018T moocOrder2018T = new MoocOrder2018T();
        moocOrder2018T.setUuid(orderId);
        moocOrder2018T.setOrderStatus(1);
        Integer result = moocOrder2018TMapper.updateById(moocOrder2018T);
        if(result >= 1){
            return true;
        }
        return false;
    }

    @Override
    public boolean payFail(String orderId) {
        MoocOrder2018T moocOrder2018T = new MoocOrder2018T();
        moocOrder2018T.setUuid(orderId);
        moocOrder2018T.setOrderStatus(0);
        Integer result = moocOrder2018TMapper.updateById(moocOrder2018T);
        if(result >= 1){
            return true;
        }
        return false;
    }
}
